from app.utils.llm_client import LLMClient
from app.utils.logger import logger
from app.prompts.algo_prompt import system_prompt, user_prompt


class LLMService:
    """LLM 服务类，用于处理与 LLM 相关的操作"""

    def __init__(self, temperature: float = 0.7):
        """
        初始化 LLM 服务
        
        Args:
            temperature (float): LLM 温度参数，控制输出的随机性
        """
        self.llm_client = LLMClient(temperature=temperature)
        self.temperature = temperature

    async def generate_code_explanation(self, code: str) -> str:
        """
        异步生成代码解释
        
        Args:
            code (str): 需要解释的代码

        Returns:
            str: 代码解释
            
        Raises:
            Exception: 当生成解释失败时抛出异常
        """
        try:
            response = await self.llm_client.get_llm_generation_async(
                client=self.llm_client.async_openai_large_client,
                model=self.llm_client.model,
                temperature=self.temperature,
                system_prompt=system_prompt,
                user_prompt=user_prompt
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            logger.error(f"生成代码解释时发生错误: {str(e)}")
            raise Exception("生成代码解释失败") from e

    def generate_code_explanation_sync(self, code: str) -> str:
        """
        同步生成代码解释
        
        Args:
            code (str): 需要解释的代码

        Returns:
            str: 代码解释
            
        Raises:
            Exception: 当生成解释失败时抛出异常
        """
        try:
            response = self.llm_client.get_llm_generation(
                client=self.llm_client.openai_large_client,
                model=self.llm_client.model,
                temperature=self.temperature,
                system_prompt=system_prompt,
                user_prompt=user_prompt,
                is_stream=False
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            logger.error(f"生成代码解释时发生错误: {str(e)}")
            raise Exception("生成代码解释失败") from e
 